$(function () {
  var configMap = {
        basePath: 'http://115.28.198.131:82/yeebrowser/api/v1/',
        page: 1,
        rows: 10
      },
      jqueryMap = {
        $wrap: $(".wapwrap"),
        $nav : $(".waplistline1")
      };

  loadNewsList();
  bindEvents();
    
  function bindEvents() {
    $(window).scroll(function(){  
      if ($(document).height() - $(this).scrollTop() - $(this).height() < 20) {
        loadNewsList();
        //renderNewsList(result.items);
      }  
    });

    jqueryMap.$nav.delegate(">div", "click", handleChangeTab);
    jqueryMap.$wrap.delegate(".newsbox", "click", handleChangeToNewsDetail);
  }

  function loadNewsList() {
    $.ajax({
      url: configMap.basePath + 'home/news/list',
      data: {
        "page": configMap.page++,
        "rows": configMap.rows
      },
      success: function (result) {
        if (result.items && result.items.length > 0) {
          renderNewsList(result.items);
        }
      }
    });
  }
  
  function renderNewsList(data) {
    var tplArr = [];

    data.forEach(function (news) {
      tplArr.push('<div class="newsbox" data-news-id="' + news.newsId + '"><div class="left">');
      tplArr.push('<img src="' + news.thumbnail + '"></div>');
      tplArr.push('<div class="right"><h6>' + news.title + '</h6>');
      tplArr.push('<p><span class="source">' + news.source + '</span><span class="date">2014-12-05 12:23:15</span></p>');
      tplArr.push('</div></div>');
    });

    jqueryMap.$wrap.append(tplArr.join(''));
  }

  function handleChangeTab(event) {
    $(this).addClass("current").siblings().removeClass("current");
  } 

  function handleChangeToNewsDetail(event) {
    var newsId = $(this).attr("data-news-id");

    window.location = './newsview.html?id=' + newsId;
  }

});